//
//  SignUpViewController.m
//  Courses
//
//  Created by xxx on 15/1/8.
//  Copyright (c) 2015年 wtf. All rights reserved.
//

#import "SignUpViewController.h"

#import "User.h"
#import "WTFFonts.h"
#import "AgreementViewController.h"
#import "PXHCountDownButton.h"
#define THEWIDTH 20
#import "WTFRootTabBarController.h"
#import "PXHStringComparison.h"
@implementation SignUpViewController
{
    UITextField *_txtUsername;
    UITextField *_txtVerificationCode;
    UITextField *_txtPassword;
    UITextField *_txtConfirmPassword;
    BOOL        _agreementIsSelected;
}

SYNTHESIZE_SINGLETON_FOR_IMPL(SignUpViewController)

- (void)viewDidLoad
{
    [super viewDidLoad];
    _agreementIsSelected = true;
    self.view.backgroundColor = [WTFColors backgroundColorLightGreen];
    
    self.title = @"注册";
    
    CGFloat rowOrigin = 15, rowHeight = 44, rowPadding = 10;
    CGFloat rowStep = rowHeight + rowPadding;
    CGFloat columnOrigin = 10, columnWidth = 100, columnWidthWide = 200;
    
    CGFloat x = columnOrigin, y = rowOrigin;
    UILabel *indicatorUsername = [[UILabel alloc] initWithFrame:AutoRectMake(x, y, columnWidth - THEWIDTH, rowHeight, WTFAutoLayoutTypeBar)];
    indicatorUsername.backgroundColor = [UIColor whiteColor];
    indicatorUsername.text = @"  手机号：";
    [self.view addSubview:indicatorUsername];
    y += rowStep;
    
    UILabel *indicatorVerificationCode = [[UILabel alloc] initWithFrame:AutoRectMake(x, y, columnWidth - THEWIDTH, rowHeight, WTFAutoLayoutTypeBar)];
    indicatorVerificationCode.backgroundColor = [UIColor whiteColor];
    indicatorVerificationCode.text = @"  验证码：";
    [self.view addSubview:indicatorVerificationCode];
    y += rowStep;
    
    UILabel *indicatorPassword = [[UILabel alloc] initWithFrame:AutoRectMake(x, y, columnWidth, rowHeight, WTFAutoLayoutTypeBar)];
    indicatorPassword.backgroundColor = [UIColor whiteColor];
    indicatorPassword.text = @"  登录密码：";
    [self.view addSubview:indicatorPassword];
    y += rowStep;
    
    UILabel *indicatorConfirmPassword = [[UILabel alloc] initWithFrame:AutoRectMake(x, y, columnWidth, rowHeight, WTFAutoLayoutTypeBar)];
    indicatorConfirmPassword.backgroundColor = [UIColor whiteColor];
    indicatorConfirmPassword.text = @"  确认密码：";
    [self.view addSubview:indicatorConfirmPassword];
    
    x += columnWidth;
    y = rowOrigin;
    _txtUsername = [[UITextField alloc] initWithFrame:AutoRectMake(x - THEWIDTH, y, columnWidth + THEWIDTH, rowHeight, WTFAutoLayoutTypeBar)];
    _txtUsername.backgroundColor = [UIColor whiteColor];
    _txtUsername.placeholder = @"手机号码";
    [self.view addSubview:_txtUsername];
    
    //获取验证码的按钮
    UIButton* timeBtn = [[UIButton alloc] initWithFrame:AutoRectMake(x + columnWidth, y, columnWidth, rowHeight, WTFAutoLayoutTypeBar)];
    [timeBtn setBackgroundImage:[UIImage imageNamed:@"btnBg1"] forState:UIControlStateNormal];
    timeBtn.exclusiveTouch = YES;
    [timeBtn setTitle:@"发送验证码" forState:UIControlStateNormal];
    timeBtn.titleLabel.textColor = [UIColor whiteColor];
    [timeBtn addTarget:self action:@selector(timeBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:timeBtn];
    //
    
    y += rowStep;
    
    _txtVerificationCode = [[UITextField alloc] initWithFrame:AutoRectMake(x - THEWIDTH, y, columnWidthWide + THEWIDTH, rowHeight, WTFAutoLayoutTypeBar)];
//    _txtUsername.placeholder = @"手机号码";
    _txtVerificationCode.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_txtVerificationCode];
    y += rowStep;
    
    _txtPassword = [[UITextField alloc] initWithFrame:AutoRectMake(x, y, columnWidthWide, rowHeight, WTFAutoLayoutTypeBar)];
    _txtPassword.placeholder = @"支持由6-30字母或数字下划线组成的密码";
    _txtPassword.backgroundColor = [UIColor whiteColor];
    _txtPassword.secureTextEntry = YES;
    [self.view addSubview:_txtPassword];
    y += rowStep;
    
    _txtConfirmPassword = [[UITextField alloc] initWithFrame:AutoRectMake(x, y, columnWidthWide, rowHeight, WTFAutoLayoutTypeBar)];
    //    _txtConfirmPassword.placeholder = @"手机号码";
    _txtConfirmPassword.backgroundColor = [UIColor whiteColor];
    _txtConfirmPassword.secureTextEntry = YES;
    [self.view addSubview:_txtConfirmPassword];
    y += rowStep;
    
    x = columnOrigin;
    y += rowPadding * 3;
    UIButton *signUpButton = [[UIButton alloc] initWithFrame:AutoRectMake(x, y + 100, DEFAULT_WIDTH - x * 2, rowHeight, WTFAutoLayoutTypeBar)];
    [signUpButton setTitle:@"登录" forState:UIControlStateNormal];
    signUpButton.backgroundColor = [WTFColors defaultIconColor];
    [signUpButton addTarget:self action:@selector(signUp) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:signUpButton];
    //选择用户协议的按钮
    UIButton* selectBtn = [[UIButton alloc]initWithFrame:AutoRectMake(3, y - 30, 150, 50, WTFAutoLayoutTypeBar)];
    [selectBtn addTarget:self action:@selector(selectAction:) forControlEvents:UIControlEventTouchUpInside];
    [selectBtn setImage:[UIImage imageNamed:@"selectBtn1.png"] forState:UIControlStateNormal];
    [selectBtn setImage:[UIImage imageNamed:@"selectBtn2.png"] forState:UIControlStateSelected];
    [selectBtn setSelected:YES];
    [self.view addSubview:selectBtn];
    //用户协议
    UIButton* userAgreement = [[UIButton alloc]initWithFrame:AutoRectMake(DEFAULT_WIDTH - 173, y - 30, 180, 50, WTFAutoLayoutTypeBar)];
    [self.view addSubview:userAgreement];
    [userAgreement setTitle:@"《益学用户服务协议》" forState:UIControlStateNormal];
    userAgreement.tintColor = [UIColor grayColor];
    [userAgreement setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [userAgreement addTarget:self action:@selector(agreementAction) forControlEvents:UIControlEventTouchUpInside];
    //保护提示
    UILabel* baohu = [[UILabel alloc] init];
    baohu.text = @"我们重视信息安全与保护，您的个人资料将不会被泄露给任何第三方的机构和个人。";
    baohu.numberOfLines = 0;
    [baohu sizeToFit];
    baohu.frame = AutoRectMake(x, y + 15, DEFAULT_WIDTH - 20, 70, WTFAutoLayoutTypeText);
    [self.view addSubview:baohu];
    //添加关闭键盘的点击手势
    UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction)];
    [self.view addGestureRecognizer:tap];
}
//
-(void)selectAction:(UIButton* )btn{
    btn.selected = !btn.selected;
    if (btn.selected) {
        NSLog(@"我被选中了");
        _agreementIsSelected = true;
    }else{
    NSLog(@"我没有被选中");
        _agreementIsSelected = false;
    }
    NSLog(@"我被点了");
}
-(void)agreementAction{
    NSLog(@"用户服务协议");
    AgreementViewController* vc = [[AgreementViewController alloc] init];
    [self.navigationController pushViewController:vc animated:NO];
}
//
- (void)signUp
{
    if (_agreementIsSelected) {
        if(![PXHStringComparison stringCheckPasswordInput:_txtPassword.text]){
             NSString* message = @"仅支持由6-30字母或数字下划线组成的密码";
             ShowTextPromptDelayHide(message, 1, self.view);
            return;
        }
       
        NSLog(@"sign up with username: %@, verification code: %@, pass: %@, confirm: %@", _txtUsername.text, _txtVerificationCode.text, _txtPassword.text, _txtConfirmPassword.text);
        
        if (_txtUsername.text.length != 11)
        {
            _txtUsername.textColor = [UIColor redColor];
            return;
        }
        if (![_txtPassword.text isEqualToString:_txtConfirmPassword.text])
        {
            _txtPassword.textColor = [UIColor redColor];
            _txtConfirmPassword.textColor = [UIColor redColor];
            [self showMBHUDWithMessage:@"两次输入的密码不一样"];
            return;
        }
        
        
        BOOL result = [User signUpWithMobile:_txtUsername.text password:_txtPassword.text verificationCode:_txtVerificationCode.text];
        
        if (result) {
            NSLog(@"signed up");
            ShowTextPromptDelayHide(@"注册成功，正在登陆！", 2.0, self.view);
            [self performSelector:@selector(loginAction) withObject:nil afterDelay:3];
        } else {
            NSLog(@"sign up failed");
            [self showMBHUDWithMessage:@"注册失败，再来一次！"];
        }
    }else{
        UIAlertView* agreenAlert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请阅读并同意益学用户服务协议！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [agreenAlert show];
    }
}

- (void)getVerificationCode
{
    NSLog(@"get verification code");
    if (_txtUsername.text.length != 11)
    {
        _txtUsername.textColor = [UIColor redColor];
        return;
    }
    
    Response* response = [User getVerificationCodeWithMobile:_txtUsername.text];
    
    if (!response.result) {
        NSLog(@"failed to get verification code");
        NSString* message = [NSString stringWithFormat:@"验证码获取失败，%@",response.msg];
        [self showMBHUDWithMessage:message];
    } else {
        NSLog(@"got verification code");
        [self showMBHUDWithMessage:@"发送成功"];
    }
}
-(void)tapAction{
    [self.view endEditing:YES];
}
-(void)httpHetworkRequest{
    [self.view endEditing:YES];
    NSString* message = nil;
    if (![PXHStringComparison stringCheckPhoneNumberInput:_txtUsername.text]) {
        message = @"请输入正确的手机号码!";
    }else if(![PXHStringComparison stringCheckPasswordInput:_txtPassword.text]){
        message = @"仅支持由6-30字母或数字下划线组成的密码";
    }
    ShowTextPromptDelayHide(message, 1, self.view);
}
-(void)timeBtnAction:(UIButton* )button{
    NSLog(@"btn =======");
    if (![PXHStringComparison stringCheckPhoneNumberInput:_txtUsername.text]) {
        [self showMBHUDWithMessage:@"请输入正确的手机号码"];
        [_txtUsername becomeFirstResponder];
        return;
    }
    else{
    [self getVerificationCode];
    }
    __block int timeout = 100; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [button setTitle:@"重新获取" forState:UIControlStateNormal];
                [button setBackgroundImage:[UIImage imageNamed:@"btnBg1"] forState:UIControlStateNormal];
                button.userInteractionEnabled = YES;
            });
        }else{
            //            int minutes = timeout / 60;
//            int seconds = timeout % 60;
//            if (seconds == 0) {
//                seconds = 60;
//            }
            NSString *strTime = [NSString stringWithFormat:@"%.2d", timeout];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                NSLog(@"____%@",strTime);
                [button setTitle:[NSString stringWithFormat:@"剩余%@秒",strTime] forState:UIControlStateNormal];
                [button setBackgroundImage:[UIImage imageNamed:@"btnBg2"] forState:UIControlStateNormal];
                button.userInteractionEnabled = NO;
                
            });
            timeout--;
            
        }
    });
    dispatch_resume(_timer);

}
-(void)loginAction{
    //注册的  同时  需要登录
    BOOL logInResult = [User signInWithMobile:_txtUsername.text password:_txtPassword.text];
    if (logInResult) {
        NSLog(@"登录成功");
//        [self.navigationController presentViewController:[WTFRootTabBarController sharedInstance] animated:NO completion:^{
//        }];
        [self.navigationController popToRootViewControllerAnimated:NO];
//        [self.navigationController popToViewController:[WTFRootTabBarController sharedInstance] animated:NO];
        
    }else{
        NSLog(@"登录失败");
    }
}
-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    
}
-(void)showMBHUDWithMessage:(NSString* )message{
    [self.view endEditing:YES];
    ShowTextPromptDelayHide(message, 1, self.view);
}
@end
